﻿package {
	
import pete.tools.Random;
import flash.display.Sprite;
import flash.events.TimerEvent;
import flash.geom.Point;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.utils.Timer;
	
	
	
public class ScreenText extends Sprite {
	
	
	
	// Properties
	// -----------------------------------------------------------
	
	public var colors:Array;
	
	private var timer:Timer;
	private var screen:Screen;
	private var textFormat:TextFormat;
	private var textField:TextField;

	private var pixelSize:Number;
	private var gateSize:Number;
	
	
	
	// Constructor
	// -----------------------------------------------------------
	
	public function ScreenText($textFormat:TextFormat = null) {
		
		if ($textFormat != null) {
			textFormat = $textFormat;
		}
		else {
			textFormat = new TextFormat();
		}
		
		setSize();
		build();
	}
	
	
	
	// Public Functions
	// -----------------------------------------------------------
	
	public function setSize($pixelSize:Number = 15, $gateSize:Number = 0):void {
		
		pixelSize 	= $pixelSize;
		gateSize	= $gateSize;
	}
	
	public function set font($value:String):void {
		
		textFormat.font = $value;
	}
	
	public function set fontSize($value:Object):void {
		
		textFormat.size = $value;
	}
	
	public function set letterSpacing($value:Object):void {
		
		textFormat.letterSpacing = $value;
	}
	
	public function set defaultTextFormat($value:TextFormat):void {
		
		textField.defaultTextFormat = $value;
	}
	
	public function set text($value:String):void {
		
		textField.htmlText = $value;
		changeColor();
		render();
	}
	
	public function get text():String {
		
		return textField.text;
	}
	
	
	
	// Private Functions
	// -----------------------------------------------------------
	
	private function build():void {
		
		colors				= [0xffffff];
		
		screen 			= new Screen();
		textField 			= new TextField();
		textField.autoSize		= TextFieldAutoSize.LEFT;
		textField.embedFonts 	= true;
		textField.defaultTextFormat = textFormat;
	}
	
	private function render():void {
		
		while (numChildren > 0) removeChildAt(0);
		
		screen.setSize		(textField.width*pixelSize, textField.height*pixelSize, pixelSize, gateSize);
		screen.draw			(textField, new Point(), 0, 1);
		screen.scaleX = screen.scaleY = (1/pixelSize) * 3;
		
		addChild			(screen);
	}
	
	
	private function setColor($color:uint):void {
		
		textField.textColor = $color;
		
		if (numChildren > 0) render();
	}
	
	
	
	// Event Handlers
	// -----------------------------------------------------------
	
	private function changeColor(te:TimerEvent = null):void {
		
		setColor(Random.chooseItemFrom(colors));
		
		if (colors.length > 1) {
			timer = new Timer(Random.choose(4000, 12000), 1);
			timer.addEventListener(TimerEvent.TIMER, changeColor);
			timer.start();
		}
	}
}

}